package natappvip.liujinliang.thread;

import java.io.File;
import java.util.concurrent.CountDownLatch;

import natappvip.liujinliang.service.FileSourceService;
import natappvip.liujinliang.service.impl.FileSourceServiceImpl;

/**
 * @ClassName:  ParalleSaveLocal   
 * @Despt: 多线程自由工作  
 * @Auth: Liujinliang 
 * @Date: 2018年7月29日 下午9:36:34
 */
public class ParalleSaveLocal {
	
	/* 规定线程数目 */
	private static final int THREAD_NUM = 5;
	
	private FileSourceService service = new FileSourceServiceImpl();

	/**
	 * @Title: parallelWrite   
	 * @Despt: 多线程存储文件   
	 * @param: @param file
	 * @param: @param metaInfoFile
	 * @param: @return
	 * @param: @throws InterruptedException      
	 * @return: int      
	 * @throws
	 */
	public int parallelWrite(File file, File metaInfoFile) throws InterruptedException {
		
		Thread[] threads = new Thread[THREAD_NUM]; // 线程数组
		
		final CountDownLatch latch = new CountDownLatch(THREAD_NUM);	
		
		for (int i = 0; i < THREAD_NUM; i++) {
			
			threads[i] = new Thread(()->{
				
				for (int j = 0; j < 1000; j++) {
					service.save(file); // 向文件写数据
				}
				
				latch.countDown();	// 子线程执行，数目减1
			});
			
			threads[i].start();
			
		}
		
		latch.await();	// 使得主线程阻塞，等到所有子线程执行完毕
		
		return 0;
	}
}
